'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 赠送体力
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var Code = require('../../../../consts/code');
var PlayerManager = require('../../../../libs/playerManager');
var constantUtil = require('../../../../util/constantUtil');
var roleService = require('../../../../services/roleService');
var taskService = require('../../../../services/taskService');

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var friend_role_id = msg.friend_role_id;

    if (!friend_role_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var friendship_value = 0;
    var my_player_manager = new PlayerManager(role_id);
    var other_player_manager = new PlayerManager(friend_role_id);
    async.waterfall(
        [
            function (cb) {
                my_player_manager.refreshData(cb);
            },
            function (cb) {
                my_player_manager.getModel(
                    ['role', 'friend', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                other_player_manager.getModel(
                    ['role', 'friend', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var my_friend_model = my_player_manager.friend;
                var other_friend_model = other_player_manager.friend;

                // 好友赠送过是否超过上限
                if (!!my_friend_model.isSendMax()) {
                    return next(null, {
                        code: Code.FRIEND_TODAY_SEND_MAX
                    });
                }

                // 好友赠送是否已经送过
                if (!my_friend_model.sendEnergy(friend_role_id)) {
                    return next(null, {
                        code: Code.FRIEND_HAVE_HAVE_PRESENT
                    });
                }
                // 增加友情值
                friendship_value = my_friend_model.addFriendshipValue();

                // 增加统计 赠送钻石
                taskService.addFriendsDiamond(my_player_manager);

                // 好友数据中记录被赠送
                other_friend_model.addPresent(role_id);
                my_player_manager.save();
                other_player_manager.save();
                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    friendship_value: friendship_value
                }
            });
        }
    );
};
